#include "CscopeParserThread.h"
#include <wx/stream.h>
#include <wx/txtstrm.h>


int wxEVT_CSCOPE_THREAD_DONE = wxNewId();

CscopeParserThread::CscopeParserThread(wxEvtHandler *notifiedWindow, const wxArrayString &output)
  : wxThread(wxTHREAD_DETACHED)
  , m_notifiedWindow(notifiedWindow)
  , m_CscopeOutput(output)
  , m_result(NULL) {
}

CscopeParserThread::~CscopeParserThread() {}

void* CscopeParserThread::Entry() {
  m_result = ParseResults();
  return NULL;
}


CscopeResultTable* CscopeParserThread::ParseResults() {
  CscopeResultTable *results = new CscopeResultTable();
  for(size_t i = 0; i < m_CscopeOutput.GetCount(); i++) {
    wxString line = m_CscopeOutput.Item(i);
    CscopeEntryData data;
    line = line.Trim().Trim(false);
    if(line.StartsWith(_T("cscope:")))
      continue;
    wxString file = line.BeforeFirst(_T(' '));
    data.SetFile(file);
    line = line.AfterFirst(_T(' '));
    line = line.Trim().Trim(false);
    wxString scope = line.BeforeFirst(_T(' '));
    line = line.AfterFirst(_T(' '));
    data.SetScope(scope);
    line = line.Trim().Trim(false);
    long nn;
    wxString line_number = line.BeforeFirst(_T(' '));
    line_number.ToLong(&nn);
    data.SetLine(nn);
    line = line.AfterFirst(_T(' '));
    wxString pattern = line;
    data.SetPattern(pattern);
    results->push_back(data);
  }
  return results;
}

void CscopeParserThread::OnExit() {
  wxCommandEvent e(wxEVT_CSCOPE_THREAD_DONE);
  e.SetClientData(m_result);
  m_notifiedWindow->AddPendingEvent(e);
}

